<?php
namespace Home\Controller;

use Org\Util\Sms;
use Org\Util\smtp;
class RegisterController extends HomeBaseController
{

    public function index()
    {
        //判断是否是推荐注册
        if(I("pusher","") != ""){
            session('pusher', I("pusher",""));
        };
        $this->display('register/index');
    }

    public function regverifyCode(){
        $type=I('type',1);
        $con=array('useNoise' => false,'length'=>4,'useCurve'=>false);
        $Verify = new \Think\Verify($con);
        $Verify->expire=120;//2分钟
        $Verify->fontSize=16;
        $Verify->entry($type);
    }
    
    /***
     * 发送注册短信
     */
    public function sendRegMobileSms(){
        $mobile=I('mobile','');
        if (!is_numeric($mobile)) {
            $this->ajaxReturn(array('code'=>'error', 'info' => '手机号码为空！'));
            exit;//0错误，1成功
        }
        else if(!preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile)) {
            $this->ajaxReturn(array('code'=>'error','info' => '手机号码格式错误！'));//0错误，1成功
            exit;
        }
        $user = D('User')->getUserByMobile($mobile);
        if($user!=null){
            $this->ajaxReturn(array('code'=>'error','info' => '此手机号码已经注册过，请直接登录！'));//0错误，1成功
            exit;
        }
        /**
         * 校验图片验证码
         * */
        $regverify=I('regverify',1);
        $imgCodeId=I('imgCodeId',1);
        $con=array('useNoise' => false,'length'=>4,'useCurve'=>false);
        $verify = new \Think\Verify($con);
        if(!$verify->check($regverify, $imgCodeId)) {
            $this->ajaxReturn(array('code'=>'error','info' => '验证码错误或已过期！'));//0错误，1成功
            exit;
        };
        $code = mt_rand(100000, 999999);
        $text = '您的验证码是：' . $code . '。此验证码1分钟内有效，请不要把验证码泄露给其他人。如非本人操作，可不用理会！';
        $send_time = time();
        $expire_time  = time() + 60;
        $sendObj=M('Sendkey')->find(1);
        $return = Sms::sendSms(array( 'content' => $text, 'mobile' => $mobile,
            'expire_time'=>$expire_time,'extra'=>$code,'sign'=>$sendObj['sign'],'todomain'=>$sendObj['todomain'],'key'=>$sendObj['key']));
        if($return=='0' || $return==0) {
            session(array('name'=>'registerCode','expire'=>70));
            session('registerCode',$code);
            $this->ajaxReturn(array('code'=>'success','info' => '获取验证码成功，请及时查看！'));//0错误，1成功
        } else {
            $this->ajaxReturn(array('code'=>'error','info' => '验证码发送失败！'));//0错误，1成功
        }
    }
    /**
     * 发送注册email
     * */
    public function sendRegEmail(){
        $email=I('email','');
        if(!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/', $email)) {
            $this->ajaxReturn(array('code'=>'error','info' => '邮箱地址格式错误！'));//0错误，1成功
            exit;
        }
        $user = D('User')->getUserByEmail($email);
        if($user!=null){
            $this->ajaxReturn(array('code'=>'error','info' => '此邮箱已经注册过，请直接登录！'));//0错误，1成功
            exit;
        }
        /**
         * 校验图片验证码
         * */
        $regverify=I('regverify',1);
        $imgCodeId=I('imgCodeId',1);
        $con=array('useNoise' => false,'length'=>4,'useCurve'=>false);
        $verify = new \Think\Verify($con);
        if(!$verify->check($regverify, $imgCodeId)) {
            $this->ajaxReturn(array('code'=>'error','info' => '验证码错误或已过期！'));//0错误，1成功
            exit;
        };
        $code = mt_rand(100000, 999999);
        $mail_title = '欢迎您注册，您的验证码';
        $mail_body = <<<Eof
尊敬的 $email 用户您好，欢迎您注册，您的验证码是 ：$code 。请在1分钟之内使用！<br/>
http://www.chengjie.com <br/>
联系电话：+86 0513-886-99963<br/>
客服邮箱: admin@chengjie.com
Eof;
        smtp::sendSmsContext($mail_body, $mail_title,$email);
        session(array('name'=>'registerCode','expire'=>70));
        session('registerCode',$code);
        $this->ajaxReturn(array('code'=>'success','info' => '邮件发送成功，请及时查看！'));//0错误，1成功
       
    }
    
    /**
     * 短信注册
     */
    public function smsregister(){
        $mobile=I('mobile','');
        $loginpasswd=I('loginpasswd','');
        $pusher=I('pusher','');
        $smscode_register=I('smscode_register','');//输入的验证码
        $code = session('registerCode');//从session里获得的验证码对象
        $sescode=strval($code);
        if($smscode_register!=$sescode){
            session('registerCode',null);
            $this->ajaxReturn(array('status'=>'2','msg' => '验证码错误或已过期！'));//0错误，1成功
            exit;
        }
        session('registerCode',null);
        $user = D('User')->getUserByMobile($mobile);
        if($user!=null){
            $this->ajaxReturn(array('status'=>'2','msg' => '此手机号码已经注册过，请直接登录！'));//0错误，1成功
            exit;
        }
        
        $User = M('User');
        $User->mobile=$mobile;
        $User->loginpasswd=md5($loginpasswd);
        if($pusher != ''){
            if(session('pusher') == ''){
                session('pusher',$pusher);
            };
        };
        $User->createdate=date("Y-m-d H:i:s ");
        $User->regfrom=1;
        // 判断是否是推荐注册
        $User = $this -> checkInvit($User);
        $result = $User->add();
        $usrAsset=M('UserAssets');
        $useAs['uid']=$result;
        $usrAsset->add($useAs);
        if($result) {
            $this -> saveInvit($result);
            $this->ajaxReturn(array('status'=>'1','redirect' => U("Login/index"),'msg'=>"注册成功！"));//0错误，1成功
            exit;
        }else{
            $this->ajaxReturn(array('status'=>'2','msg' => '注册失败！'));//0错误，1成功
            exit;
        }
    }
    
    /**
     * email注册
     */
    public function emailregister(){
        $email=I('email','');
        $loginpasswd=I('loginpasswd','');
        $pusher=I('pusher','');
        $smscode_register=I('smscode_register','');
        
        $code = session('registerCode');
        
        if($smscode_register!=strval($code)){
           session('registerCode',null);
           $this->ajaxReturn(array('status'=>'2','msg' => '验证码错误或已过期！'));//0错误，1成功
           exit;
        }
        session('registerCode',null); // 删除name
        
        $user = D('User')->getUserByEmail($email);
        if($user!=null){
            $this->ajaxReturn(array('status'=>'2','msg' => '此邮箱已经注册过，请直接登录！'));//0错误，1成功
            exit;
        }
        
        $User = M('User');
        $User->email=$email;
        $User->loginpasswd=md5($loginpasswd);
        if($pusher != ''){
            if(session('pusher') == ''){
                session('pusher',$pusher);
            };
        };
        $User->createdate=date("Y-m-d H:i:s ");
        $User->regfrom=1;
        // 判断是否是推荐注册
        $User = $this -> checkInvit($User);
        $result = $User->add();
        $usrAsset=M('UserAssets');
        $useAs['uid']=$result;
        $usrAsset->add($useAs);
        if($result) {
            $this -> saveInvit($result);
            $this->ajaxReturn(array('status'=>'1','redirect' => U("Login/index"),'msg'=>"注册成功！"));//0错误，1成功
            exit;
        }else{
            $this->ajaxReturn(array('status'=>'2','msg' => '注册失败！'));//0错误，1成功
            exit;
        }
    }
    
    // 判断是否是推荐注册
    public function checkInvit($User){
        if ('' != session('pusher')) {
            $cond['invit_code'] = session('pusher');
            $userInvit = D('user')->field(true)->where($cond)->find();
            if(null != $userInvit){
                $User->pusherid=$userInvit["id"];
            };
        };
        $User->invit_code=substr(md5(uniqid(mt_rand(), true)),0,6);// 生成用户唯一邀请码
        session('pusher',null);
        return $User;
    }
    
    // 判断推荐用户是否添加推荐用户注册收入,没添加则添加记录
    public function saveInvit($id){
        $cond['id'] = $id;
        $user = D('user')->field(true)->where($cond)->find();
        if(null != $user["pusherid"]){
            $arr=array('uid'=>$user["pusherid"],'register_uid' => $id,'register_date'=> $user["createdate"]);
            D('RecommedIncome')->inst($arr);
        };
    }
}